﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using iFinity.DNN.Modules.UrlRedirectProvider.Entities;
using iFinity.DNN.Modules.UrlMaster;
using iFinity.DNN.Modules.UrlMaster;
namespace iFinity.DNN.Modules.UrlRedirectProvider 
{
    public class UrlRedirectProvider : ModuleFriendlyUrlProvider
    {
        #region private members
        FriendlyUrlOptions _options = null; //local copy of the Friendly Url Options, which control things like the inclusion of hyphens instead of spaces, etc.
        //the following set of members are specific to this module, and are used to control how the module provider works.
        //these are read from the web.config file, and appear as attributes in the Module Provider declaration
        protected int _noDnnPagePathTabId = -1; //- used to specify if the  module is on a page where the page path should not be included in the url.
        protected string _urlPath;//- specifies the url path to use for a UrlRedirectProvider Url
        protected string _ignoreRedirectRegex;//-a regex pattern to ignore certain Urls that will not be redirected
        
        #endregion

        #region overridden methods and properties
        /// <summary>
        /// Constructor for the UrlRedirect Url Provider.  This is called by the Url Master module when loading the Provider
        /// </summary>
        /// <param name="name">Name is supplied from the web.config file, and specifies the unique name of the provider</param>
        /// <param name="attributes">Attributes are the xml attributes from the file</param>
        /// <param name="portalId">The portalId is supplied for the calling portal.  Each instance of the provider is portal specific.</param>
        public UrlRedirectProvider(string name, NameValueCollection attributes, int portalId)
            : base(name, attributes, portalId)
        {
            //look for an attribute specifying which tab the module
            //will not use a page path for.  There can only be one
            //tab specified per portal (because there is no page path, then it
            //can only be a single page, as the way of determining one dnn
            //page from another isn't in the reuqested Url)
            string noDnnPagePathTabRaw = attributes["noDnnPagePathTabId"];
            int.TryParse(noDnnPagePathTabRaw, out _noDnnPagePathTabId);
            _ignoreRedirectRegex = attributes["ignoreRedirectRegex"];
            _urlPath = attributes["urlPath"];
        }
        /// <summary>
        /// The Change Friendly Url method is called for every Url generated when a page is generated by DotNetNuke.  This call sits 'underneath' the 'NavigateUrl' call in DotNetNuke.
        /// Whenever your module calls NavigateUrl, this method will be also called.  In here, the module developer should modify the friendlyUrlPath to the final state required.
        /// However, because this call is used for all Urls on the page, not just those generated by the target module, some type of high-level filter should be used to make sure only
        /// the module Urls are modified.
        /// 
        /// </summary>
        /// <param name="tab">Current Tab</param>
        /// <param name="friendlyUrlPath">Current Friendly Url Path after going through the Friendly Url Generation process of the Url Master module.</param>
        /// <param name="options">The options currently applying to Urls in this portal (space replacement, max length, etc)</param>
        /// <param name="cultureCode">The culture code being used for this Url (if supplied, may be empty)</param>
        /// <param name="endingPageName">The page name the Url has been called with. Normally default.aspx, but may be different for some modules.</param>
        /// <param name="useDnnPagePath">Out parameter to be set by the module.  If true, the path of the DNN page will be in the Url (ie /pagename).  If false, this part of the Url will be removed. </param>
        /// <param name="messages">List of debug messages.  Add any debug information to this collection to help debug your provider.  This can be seen in the repsonse headers, and also in the 'test Url Rewrite' page in the Url Master module.</param>
        /// <returns></returns>
        public override string ChangeFriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string friendlyUrlPath, FriendlyUrlOptions options, string cultureCode, ref string endingPageName, out bool useDnnPagePath, ref List<string> messages)
        {
            //no modifications to urls for this provider   
            useDnnPagePath = true;
            return friendlyUrlPath;
        }
        /// <summary>
        /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
        /// </summary>
        /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
        /// <param name="tabId">TabId of identified DNN page. </param>
        /// <param name="portalId">PortalId of identified DNN portal.</param>
        /// <param name="options">The current Friendly Url options being used by the module.</param>
        /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
        /// <param name="portalAlias">Identified portalAlias object for the request.</param>
        /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
        /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
        /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
        /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns>
        public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List<string> messages, out int status, out string location)
        {
            //no rewriting for this provider
            location = null;
            status = 200;
            return "";
        }

        /// <summary>
        /// Determines when to do a redirect.  This is separate to the rewriting process.  The module developer can create any type of Url redirect here, because the entire Url of the original request is passed in.
        /// </summary>
        /// <param name="tabId">Identified TabId, if known.  -1 if no valid tabid identified.</param>
        /// <param name="portalid">Identified portalId.</param>
        /// <param name="httpAlias">Identified httpAlias of the request.</param>
        /// <param name="requestUri">The original requested Url</param>
        /// <param name="queryStringCol">The querystring collection of the original request</param>
        /// <param name="options">The friendly url options that currently apply.</param>
        /// <param name="redirectLocation">Out parameter that shows where to redirect to.</param>
        /// <param name="messages">List of messages for debug purposes.  Add to this list to help debug your module.</param>
        /// <returns>true if 301 redirect is required, false if not.  If true, the redirectLocation value must be a valid fully qualified Url.</returns>
        public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, System.Collections.Specialized.NameValueCollection queryStringCol, FriendlyUrlOptions options, out string redirectLocation, ref List<string> messages)
        {
            bool doRedirect = false;
            redirectLocation = "";//set blank location
            //compare to known pattern of old Urls
            //could be in old /itemid/xx format - if so, we want to redirect it
            bool checkForRedirect = true;
            string path = requestUri.AbsoluteUri;
            if (string.IsNullOrEmpty(_ignoreRedirectRegex) == false)
            {
                Regex ignoreRegex = new Regex(_ignoreRedirectRegex, RegexOptions.IgnoreCase);
                Match ignoreRegexMatch = ignoreRegex.Match(path);
                checkForRedirect = !(ignoreRegexMatch.Success);
            }
            if (checkForRedirect)
            {

                List<RedirectInfo> regexIndex; Hashtable redirectIndex;
                UrlController.GetRedirectIndexes(portalid, this, options, out redirectIndex, out regexIndex);

                //try out the various different forms of redirect that are allowed
                //first is an absolute match
                string absoluteUrl = UrlController.StripSchemeFromUrl(requestUri);
                string absolutePath = UrlController.StripSchemeAndQueryStringFromUrl(requestUri);
                string key = absoluteUrl.ToLower();
                string key2 = absolutePath.ToLower();
                if (redirectIndex.ContainsKey(key))
                {
                    //match on all of path!  this means we will be redirecting
                    redirectLocation = UrlController.RedirectLocation((RedirectInfo)redirectIndex[key], absoluteUrl, requestUri.Scheme, queryStringCol , ref messages);
                    doRedirect = true;
                }
                if (!doRedirect && redirectIndex.ContainsKey(key2))
                {
                    //match with no querystring!  this means we will be redirecting
                    redirectLocation = UrlController.RedirectLocation((RedirectInfo)redirectIndex[key2], absoluteUrl, requestUri.Scheme, queryStringCol, ref messages);
                    doRedirect = true;
                }
                if (!doRedirect)
                {
                    //check for relative path
                    string relativeUrl = UrlController.StripAliasFromUrl(absoluteUrl, httpAlias);
                    string relativePath = UrlController.StripAliasFromUrl(absolutePath, httpAlias);
                    key = relativeUrl.ToLower();
                    key2 = relativePath.ToLower();
                    if (redirectIndex.ContainsKey(key))
                    {
                        redirectLocation = UrlController.RedirectLocation((RedirectInfo)redirectIndex[key], relativeUrl, requestUri.Scheme, queryStringCol, ref messages);
                        doRedirect = true;
                    }
                    if (!doRedirect && redirectIndex.ContainsKey(key2))
                    {
                        redirectLocation = UrlController.RedirectLocation((RedirectInfo)redirectIndex[key2], relativeUrl, requestUri.Scheme, queryStringCol, ref messages);
                        doRedirect = true;
                    }
                }
                if (!doRedirect)
                {
                    if (regexIndex != null && regexIndex.Count > 0)
                    {
                        foreach (RedirectInfo regexRedirect in regexIndex)
                        {
                            //check each regex pattern sequentially
                            UrlController.CheckRegexRule(regexRedirect, requestUri.AbsoluteUri,  requestUri.Scheme,  queryStringCol, out doRedirect, out redirectLocation, ref messages);
                            if (doRedirect) break;
                        }
                    }
                }
            }

            return doRedirect;
        }

        public override string FriendlyName
        {
            get { return "iFinity UrlRedirect Friendly Url Provider"; }
        }
        /// <summary>
        /// Returns any custom settings that are specific per-portal for this instance
        /// </summary>
        /// <remarks>
        /// This is used to write the values back out to the web.config from the Url Master UI
        /// </remarks>
        /// <returns>A Dictionary of the key/value pairs of the settings used in this provider.  Return empty dictionary if no portal specific options.</returns>
        public override Dictionary<string, string> GetProviderPortalSettings()
        {
            //returns the settings specific to this portal instance
            Dictionary<string, string> settings = new Dictionary<string, string>();
            if (_urlPath != null && _urlPath != "")
                settings.Add("urlPath", _urlPath);
            if (_noDnnPagePathTabId > 0)
                settings.Add("noDnnPagePathTabId", _noDnnPagePathTabId.ToString());
            return settings;
        }

        public override bool AlwaysUsesDnnPagePath(int portalId)
        {
            if (_noDnnPagePathTabId > -1)
            {
                return false;//if there is an exception, then return false
            }
            else
                return true;//no specific exceptions, return true every time
        }
        public override bool AlwaysCallForRewrite(int portalId)
        {
            return false;
        }
        public override bool IsLicensed(Uri requestUri, out string messageHtml, out string debugMessage)
        {
            //If this module had a licensing requirement, it would be checked here.  If not licensed
            //return false, and return some Html to be included on any pages where the provider is used, ie:
            //messageHtml = "<div>Hey! this isn't licensed!</div>"; debugMessage = "Fake licence message";
            //return false;

            //but in this case, there's no licensing restrictions with this provider, so always return true
            //and return nothing for the messagehtml and debugmessage
            messageHtml = null; debugMessage = null;
            return true; 
        }
        /// <summary>
        /// Returns the Path of the Settings .ascx control (if supplied).  The Settings control is loaded by the Portal Urls page for the provider,
        /// and allows interaction of the settings by the end user, at a per-portal level.
        /// </summary>
        /// <remarks>
        /// Return empty or null string if no control exists.  The path should match the path specified in the DNN install manifest, and 
        /// point to an actual file.
        /// </remarks>
        public override string SettingsControlSrc
        {
            get { return "DesktopModules/iFinity_UrlRedirectProvider/Settings.ascx"; }
        }
        

#endregion
        #region internal methods and properties
        internal new string CleanNameForUrl(string title, FriendlyUrlOptions options)
        {
            bool replaced = false;
            //the base module Url PRovider contains a Url cleaning routine, which will remove illegal and unwanted characters from a string, using the specific friendly url options
            return base.CleanNameForUrl(title, options, out replaced);
        }
        #endregion

        internal int NoDnnPagePathTabId {
            get { return _noDnnPagePathTabId; }
            set { _noDnnPagePathTabId = value; }
        }

        internal string UrlPath {
            get { return _urlPath; }
            set { _urlPath = value; }
        }
    }
}
